package com.dhl.commonutils.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dhl.commonutils.jwt.JwtUtils;
import com.dhl.commonutils.R;
import com.dhl.entity.SysMenu;
import com.dhl.entity.SysRole;
import com.dhl.entity.SysUser;
import com.dhl.service.SysMenuService;
import com.dhl.service.SysRoleService;
import com.dhl.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 登录成功处理器
 * @title: LoginSuccessHandler
 * @Author danghailiang
 * @Date: 2022/10/14 21:13
 * @Version 1.0
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * 用户服务
     */
    @Resource
    private SysUserService sysUserService;
    /**
     * 角色服务
     */
    @Resource
    private SysRoleService sysRoleService;
    /**
     * 菜单服务
     */
    @Resource
    private SysMenuService sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 设置响应类型
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        // 获取输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username = authentication.getName();
        String jwtToken = JwtUtils.getJwtToken("1", username);

        // 获取登录用户信息
        SysUser sysUser = sysUserService.getSysUserByUsername(username);
        // 获取所有的角色列表
        List<SysRole> roleList = sysRoleService.list(new LambdaQueryWrapper<SysRole>()
                .inSql(SysRole::getId,"select role_id from sys_user_role where user_id =" + sysUser.getId())
        );
        // 根据角色列表获取菜单
        List<SysMenu> menus =  sysMenuService.getMenuListByRole(roleList);
        sysUser.setPassword(null);
        R r = R.ok()
                .data("userinfo",sysUser)
                // 返回菜单
                .data("menus",menus)
                // 返回token
                .data("authorization", jwtToken);

        // 返回数据
        outputStream.write(JSONUtil.toJsonStr(r).getBytes(StandardCharsets.UTF_8));
        // 刷新缓存
        outputStream.flush();
        // 关闭流
        outputStream.close();
    }

}
